
import { Component, OnInit, ChangeDetectorRef, Input, Output, EventEmitter } from '@angular/core';
import { CommonService } from '../../common.service';
import { HttpClient } from '@angular/common/http';
import { LoadingController, ActionSheetController, AlertController } from '@ionic/angular';
import { environment } from 'src/environments/environment';
import { FileTransferObject, FileTransfer, FileUploadOptions } from '@ionic-native/file-transfer/ngx';
import { PhotoViewer } from '@ionic-native/photo-viewer/ngx';

@Component({
  selector: 'app-img-upload',
  templateUrl: './img-upload.component.html',
  styleUrls: ['./img-upload.component.scss'],
})
export class ImgUploadComponent implements OnInit {
  @Input() imgList: string[]=[];
  @Input() limit:1;
  @Input() type:0;
  @Input() isViewMode:false;
  @Output() private outer = new EventEmitter<any>();
  list = [];
  defaultImgSrc='assets/imgs/upimg.jpg';
  imageResult:{
    imageList:string[],
    ocrString:string
  };

  constructor(
    private commonService: CommonService,
    private transfer: FileTransfer,
    private http: HttpClient,
    private loadingController: LoadingController,
    private alertController: AlertController,
    private photoViewer: PhotoViewer,
    public actionSheetController: ActionSheetController,
    public ref: ChangeDetectorRef) { }

  ngOnInit() {
    this.addDefaultImage();
  }

  /**
   * 添加默认图片
   */
  addDefaultImage(){
    if(this.imgList==null || this.imgList.length===0 || this.imgList[0]==='' ){
      this.imgList[0]=this.defaultImgSrc;
    }
    for (let index = 0; index < this.limit-this.imgList.length; index++) {
      this.imgList.push(this.defaultImgSrc);
    }
  }

  // 像父组件返回值
  sendUrl(imgList:string[],ocrString:string) {
    const data={imgList:[],ocrString:''};
    data.imgList=imgList;
    data.ocrString=ocrString;
    this.outer.emit(data);
  }

  /**
   * 编辑时单击
   */
  async onEditClick(item) {
    const actionSheet = await this.actionSheetController.create({
      header: '图片上传',
      cssClass: '',
      buttons: [{
        text: '相机',
        icon: 'camera',
        handler: () => {
          this.takePhoto(item);
        }
      }, {
        text: '图库',
        icon: 'images',
        handler: () => {
          this.chooseImage(item);
        }
      }, {
        text: '删除',
        icon: 'trash',
        handler: () => {
          const index=this.imgList.indexOf(item);
          if(index>-1){
            this.imgList.splice(index,1);
          }
          this.imgList.push(this.defaultImgSrc);
          this.sendUrl(this.imgList,'');
        }
      }, {
        text: '查看',
        icon: 'eye',
        handler: () => {
          this.photoViewer.show(item);
        }
      }, {
        text: '取消',
        icon: 'arrow-undo',
        role: 'cancel',
        handler: () => {
          // this.sendUrl(this.imgList);
        }
      }]
    });
    await actionSheet.present();
  }

  /**
   * 查看时单击
   */
  async onViewClick(item) {
    const actionSheet = await this.actionSheetController.create({
      header: '图片查看',
      cssClass: '',
      buttons: [ {
        text: '查看',
        icon: 'eye',
        handler: () => {
          this.photoViewer.show(item);
        }
      }, {
        text: '取消',
        role: 'cancel',
        icon: 'arrow-undo',
        handler: () => {
          // this.sendUrl(this.imgList);
        }
      }]
    });
    await actionSheet.present();
  }


  // 选择图片，选择完成立即上传
  chooseImage(item) {
    this.commonService.getPictureByPhotoLibrary().subscribe(async res => {
      await this.uploadImg(res, item);
      console.log('选择图片地址：',res);
    })
  }

  // 拍照上传
  takePhoto(item) {
    this.commonService.getPictureByCamera().subscribe(async res => {
      await this.uploadImg(res, item);
      console.log('拍照图片：',res);
    })
  }

  // 上传图片
  async uploadImg(fileURL, item) {
    const _this = this;
    const loading = await _this.loadingController.create({
      cssClass: 'my-custom-class',
      message: '努力上传中...',
      duration: 15000
    });
    await loading.present();

    // let url = encodeURI(environment.SERVER_URL + '/api/Vehicle/UploadFiles');
    const url = encodeURI(environment.SERVER_URL+`/api/BaiduOcr/UploadFiles?type=${this.type}`);

    const options: FileUploadOptions = {};
    options.fileKey = 'file';
    options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
    options.mimeType = 'text/plain';
    // options.params = {};// 自定义参数
    const fileTransfer: FileTransferObject = _this.transfer.create();
    let timer = null;// 由于onProgress事件调用非常频繁,所以使用setTimeout用于函数节流
    fileTransfer.onProgress(async progressEvent => {
      if (progressEvent.lengthComputable) {
        const progress = Math.floor(progressEvent.loaded / progressEvent.total * 100);// 下载进度
        if (progress === 100) {
          await loading.onDidDismiss();
        } else {
          if (!timer) {
            timer = setTimeout(() => {
              clearTimeout(timer);
              timer = null;
              const title = document.getElementsByClassName('loading-content')[0];
              // tslint:disable-next-line: no-unused-expression
              title && (title.innerHTML = `上传进度：${progress}%`);
            }, 1000);
          }
        }
      } else {
        // loadingStatus.increment();
      }
    });
    fileTransfer.upload(fileURL, url, options).then(async (r: any) => {
      loading.onDidDismiss();
      _this.commonService.presentToast('上传成功');
      const response = JSON.parse(r.response);
      console.log(response);
      const imgUrl = response.url;
      const ocrString=response.ocr_result;
      this.imgList.push(imgUrl);
      // 清除之前图片
      const index=this.imgList.indexOf(item);
      if(index>-1){
        this.imgList.splice(index,1);
      }
      this.sendUrl(this.imgList,ocrString);
      _this.ref.detectChanges();
    }).catch(async error => {
      await loading.onDidDismiss();
      _this.commonService.presentToast('失败:' + error);
      return 'err';
    });
  }

}

